package com.atguigu.sink;

import com.atguigu.bean.WaterSensor;
import com.atguigu.function.WaterSensorFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * @author yhm
 * @create 2024-04-03 15:19
 */
public class Test05_MySinkFunction {
    public static void main(String[] args) throws Exception {
        // 1. 创建环境
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",8081);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 2. 读取数据源
        DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 7777);

        // 3. 处理数据

        SingleOutputStreamOperator<WaterSensor> beanStream = streamSource.flatMap(new WaterSensorFunction());
        // 4. 输出
        beanStream.addSink(new SinkFunction<WaterSensor>() {

            Connection connection ;

            @Override
            public void invoke(WaterSensor value, Context context) throws Exception {
                // 手写jdbcSink
                // 1. 获取连接
                if (connection == null){
                    connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8","root","000000");
                }

                // 2. 编译sql
                PreparedStatement ps = connection.prepareStatement(
                        "insert into ws (id,ts,vc)" + "values ('" + value.id + "'," + value.ts + "," + value.vc + ")"

                )
                        ;
                ps.execute();
                ps.close();

            }

            @Override
            public void finish() throws Exception {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
        });

        // 5. 执行环境
        env.execute();
    }
}
